package com.rtx.common;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Helper {
	/**
	 * MD5加密
	 * @param data
	 * @param encode
	 * @return
	 */
	public static byte[] encryptMD5(String data,String encode) {
		byte[] b = {};
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(data.getBytes(encode));
	        b = md.digest();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}
	/**
	 * MD5+16进制转换
	 * @param data
	 * @return
	 */
	public static String encryptMD5And16Hex(String data) {
		byte[] b = encryptMD5(data,"utf-8");
		StringBuffer buffer = new StringBuffer(32);
		for (int i = 0; i < b.length; i++) {
			String temp = Integer.toHexString(b[i] & 0xff);
			 if (temp.length() < 2) {
				 buffer.append("0");
			 }
			 buffer.append(temp);
		}
		return buffer.toString();
	}
	
	
	// 将 s 进行 BASE64 编码 
	 public static String to64(String s) { 
	  if (s == null) return null; 
	  try {
	   return (new sun.misc.BASE64Encoder()).encode( s.getBytes("utf-8") );
	  } catch (UnsupportedEncodingException e) {
	   e.printStackTrace();
	   return "";
	  } 
	 } 
	 
	 public static String ToMD5and32(String sourceStr) {
	        String result = "";
	        try {
	            MessageDigest md = MessageDigest.getInstance("MD5");
	            md.update(sourceStr.getBytes());
	            byte b[] = md.digest();
	            int i;
	            StringBuffer buf = new StringBuffer("");
	            for (int offset = 0; offset < b.length; offset++) {
	                i = b[offset];
	                if (i < 0)
	                    i += 256;
	                if (i < 16)
	                    buf.append("0");
	                buf.append(Integer.toHexString(i));
	            }
	            result = buf.toString();
	            /*System.out.println("MD5(" + sourceStr + ",32) = " + result);*/
	        } catch (NoSuchAlgorithmException e) {
	            System.out.println(e);
	        }
	        return result;
	    }
}
